package com.zhangkeyou.map.mapweb.controller;

import com.zhangkeyou.map.mapweb.domain.entity.LoginUser;
import com.zhangkeyou.map.mapweb.domain.entity.Status;
import com.zhangkeyou.map.mapweb.domain.entity.Userinfo;
import com.zhangkeyou.map.mapweb.service.UserinfoService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/api/userinfo")
public class UserinfoController {
//    OFF、FATAL、ERROR、WARN、INFO、DEBUG、TRACE、 ALL
private static final Logger LOGGER = LoggerFactory.getLogger(UserinfoController.class);


    @Autowired
    private UserinfoService userinfoService;


    @Autowired
    PasswordEncoder passwordEncoder;
    @GetMapping("/getInfo")
    public Status getInfo(){
//        Userinfo userinfo = userinfoService.getInfo(userToken);

        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(Objects.isNull(loginUser))
            throw new RuntimeException("未登录");
        String userId = loginUser.getUserinfo().getId();

        //todo 添加用户信息
        Status status = userinfoService.getUserInfo(userId);
        if(loginUser!=null)
        {
            LOGGER.info(String.format("%s通过获得信息",loginUser.getUsername()));
            status.setData(loginUser.getUserinfo());
            status.setState(200);
            status.setMsg("success");
        }else{
            LOGGER.info(String.format("获得信息失败"));

            status.setState(400);
            status.setMsg("out time");
        }
        return status;
    }

    public static String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    @PostMapping("/login")
//    public Status login(@RequestBody Userinfo userinfo){
    public Status login(@RequestBody Userinfo userinfo){
//
        try{
            return userinfoService.login(userinfo);
        }catch (BadCredentialsException badCredentialsException){
            return new Status(400,badCredentialsException.getMessage(),badCredentialsException.getMessage());
        }catch (Exception exception){
            log.info("密碼錯誤");
            return new Status(400,exception,"账户或密码不正确2");
        }
/*
        Userinfo userinfo = new Userinfo();
        userinfo.setUsername(username);
        userinfo.setPassword(MyUtils.getMD5(password));

        Userinfo login = userinfoService.login(userinfo);
        Status status = new Status();
        if(login==null){
            log.info(String.format("来自%s的%s--%s登录失败",getRemortIP(request),username,password));

            status.setState(400);
            status.setMsg("用户名或者密码错误");

        }else{
            log.info(String.format("来自%s的%s--%s登录成功",getRemortIP(request),username,password));

            status.setData(login);
            status.setState(200);
        }
        return status;*/
    }
    @PostMapping("/register")
/*    public Status Register(@RequestBody Userinfo userinfo) {
        return null;
    }*/
    public Status register(@RequestBody Userinfo userinfo){
        Status status = userinfoService.register(userinfo);

/*        Userinfo userinfo = new Userinfo();
        userinfo.setUsername(username);
        userinfo.setPassword(passwordEncoder.encode(password));
        if(userinfoService.exitsUserinfo(userinfo)){
            return new Status<>(400,null,"error");
        }
        userinfo.setId(UUID.randomUUID().toString());
        try{
//            userinfo.setHeader_pic(header_pic);
            userinfo.setHeader_pic(header_pic);
        }catch (Exception ex){
            log.error("设置账户的image失败"+ex.getMessage());
            ex.printStackTrace();
        }
        Status status = userinfoService.register(userinfo);
        */
        return status;
    }

    @GetMapping("/authorities")
    public Status getAuth(){
        try{
            return userinfoService.getAuthorities();
        }catch (Exception ex){
            return new Status<>(400,ex.getMessage(),"error");
        }
    }

    @PostMapping("/logout")
    public Status logout(){
        return userinfoService.logout();
    }

    @PostMapping("/updateUserHeader")
    public Status updateHeader(@RequestBody Userinfo userinfo){
        return userinfoService.updateHeader(userinfo.getHeader_pic());
    }

    @PostMapping("/updateUserPassword")
    public Status updatePassword(@RequestBody Userinfo userinfo){
        return userinfoService.updatePassword(userinfo.getPassword());
    }

}
